<template>
  <div class="container" @scroll="handleScroll">
    <navigate>
      普通测评记录

      <template v-slot:right>
        <!-- <img class="search" src="@/assets/images/evaluate/search.png" alt="" /> -->
      </template>
    </navigate>

    <search-input
      class="search_input"
      type="text"
      v-model="value"
      placeholder="搜索咨询师姓名或咨询内容"
    ></search-input>
    <template v-for="(item, index) in list.combine">
      <div class="title flex_row flex_align_center" :key="index">
        <div class="bar"></div>
        <div class="date">{{ item.key }}</div>
      </div>
      <div
        class="card"
        v-for="(e, i) in item.value"
        @click="
          operateVisible = true;
          currentExport = e;
        "
        :key="`${i}-${index}-${e.id}`"
      >
        <div class="card_top flex_row flex_align_start">
          <div class="cover">
            <img :src="joinUrlImg(e.icon_url)" alt="" />
          </div>
          <div class="card_top_right">
            <div class="name_new flex_row flex_align_center between">
              <div class="text nowrap">{{ e.rating_scale_name }}</div>

              <!-- <div class="new" v-if="newPublish(e.create_time)">新</div> -->
            </div>
            <div class="label flex_row flex_align_center">
              <div>
                {{ (e.is_parent_test == 0 ? "本人" : "家长") + "答题" }}
              </div>
              <div v-if="e.is_interpret == 1">报告已解读</div>
            </div>
            <div class="jurisdiction flex_row flex_align_center">
              <div class="text">查看权限：</div>

              <div class="user flex_row flex_align_center">
                <img
                  :src="
                    require(`@/assets/images/evaluate/radio${
                      e.read_auth.split(',').includes('3') ? 2 : 1
                    }.png`)
                  "
                  alt=""
                />用户本人
              </div>
              <div class="patriarch flex_row flex_align_center">
                <img
                  :src="
                    require(`@/assets/images/evaluate/radio${
                      e.read_auth.split(',').includes('4') ? 2 : 1
                    }.png`)
                  "
                  alt=""
                />用户家长
              </div>
            </div>
          </div>
        </div>
        <div class="card_bottom flex_row flex_align_center between">
          <div class="text">测评整体评分：{{ e.total_score }}分</div>
          <button class="btn nowrap" @click.stop="lookExport(e)">
            查看报告
          </button>
        </div>
      </div>
    </template>
    <patriarch-login
      @confirm="look"
      :visible="show"
      @close="show = $event"
      v-model="patriarchPassword"
    ></patriarch-login>
    <popup-slot-operate
      :visible.sync="operateVisible"
      :options="options"
      @click="clickItem"
    ></popup-slot-operate>
  </div>
</template>

<script>
import searchInput from "@/components/searchInput/index.vue";
import popupSlotOperate from "@/components/popupSlotOperate/index.vue";
import patriarchLogin from "../../components/index.vue";
import { apiVerifyParentPassword } from "@/api/user";
import {
  apiGetNormalEvaluateExport,
  apiDeleteExport,
  getReportJurisdiction,
} from "@/api/report.js";
import { mapState } from "vuex";
import { formatDate } from "@/utils/time";
import { debounce } from "@/utils/debounce";
import { joinUrlImg } from "@/utils/setUrlImg";
export default {
  components: {
    "search-input": searchInput,
    "popup-slot-operate": popupSlotOperate,
    "patriarch-login": patriarchLogin,
  },
  computed: {
    ...mapState(["INFO"]),
    // 判断是否为新发布
    newPublish() {
      return (date) => {
        const time = new Date().getTime();
        const base = 1000 * 60 * 60 * 24;
        if (time - date * 1000 < base) return true;

        return false;
      };
    },
  },
  watch: {
    value(nv) {
      this._debounce();
    },
  },
  data() {
    return {
      // 家长密码
      patriarchPassword: "",
      show: false,
      _debounce: null,
      // 搜索参数
      value: "",
      operateVisible: false,
      options: ["查看详情", "删除报告"],
      // 列表
      list: [],
      // 获取测评列表的参数
      params: {
        page: 1,
        page_size: 9998,
      },
      // 选中的报告
      currentExport: "",
    };
  },
  methods: {
    joinUrlImg,
    handleScroll(e) {
      const container = e.target;
      // 容器高度
      const containerHeight = container.clientHeight;
      // 内容高度
      const contentHeight = container.scrollHeight;
      // 当前滚动位置
      const scrollTop = container.scrollTop;

      // 判断是否滚动到底部（留出10px的缓冲）
      if (scrollTop + containerHeight >= contentHeight - 10) {
      }
    },
    // 查看报告
    async look() {
      // 验证家长密码
      const { data } = await apiVerifyParentPassword({
        password: this.patriarchPassword,
      });
      if (data.code == 200) {
        // 验证密码正确
        this.$router.push(`/evaluateExport/${this.currentExport.id}`);
      }
    },
    // 搜索
    search() {
      this._debounce = debounce(() => {
        this.getNormalEvaluateExport();
      }, 500);
    },
    async lookExport(r) {
      this.currentExport = r;
      const { data } = await getReportJurisdiction({ id: r.id, type: 1 });
      if (data.code == 200) {
        this.$router.push(`/evaluateExport/${r.id}`);
      } else if (data.code == 402) {
        this.show = true;
      } else {
        this.$toast.fail("没有查看的权限!");
      }
    },
    mergedArray(arr) {
      let map = new Map();
      let temp = [];
      arr.forEach((item) => {
        let date = formatDate(
          new Date(item.create_time * 1000),
          "yyyy年MM年dd日"
        );
        map.has(date) ? map.get(date).push(item) : map.set(date, [item]);
      });
      Array.from({ length: [...map.keys()].length }, (item, index) => {
        temp.push({
          key: [...map.keys()][index],
          value: [...map.values()][index],
        });
      });
      return {
        key: [...map.keys()],
        value: [...map.values()],
        combine: temp,
      };
    },
    async getNormalEvaluateExport() {
      const params = {
        company_id: this.INFO.platform_unit_id,
        ...this.params,
        search_key: this.value,
      };
      const { data } = await apiGetNormalEvaluateExport(params);
      if (data.code == 200) {
        this.list = this.mergedArray(data.data.list);
      }
    },
    async clickItem(r) {
      if (r == "申请解读") {
        this.$popup({
          visible: false,
          title: "申请解读",
          message: `<div>申请解读可以得到咨询师对本报告的</div>
          <div>建议及意见。确定要向<span>黄老师</span>申请吗?</div>
            <div style="white-space: nowrap;font-size: 16px;color: #959595;">(今日剩余申请次数：3次)</div>
          `,
          confirmOperate: async () => {},
        });
      } else if (r == "删除报告") {
        const params = {
          ids: this.currentExport.id,
          company_id: this.INFO.platform_unit_id,
          type_id: 1,
        };
        this.$popup({
          visible: false,
          title: "申请解读",
          message: `<div>确定要删除此报告吗？</div>
         
          `,
          confirmOperate: async () => {
            const { data } = await apiDeleteExport(params);
            if (data.code == 200) {
              this.$toast.success("删除成功！");
              this.getNormalEvaluateExport();
            }
          },
        });
      } else {
        const { data } = await getReportJurisdiction({
          id: this.currentExport.id,
          type: 1,
        });
        if (data.code == 200) {
          this.$router.push(`/evaluateExport/${this.currentExport.id}`);
        } else if (data.code == 402) {
          this.show = true;
        } else {
          this.$toast.fail("没有查看的权限!");
        }
      }
      this.operateVisible = false;
    },
  },
  created() {
    this.getNormalEvaluateExport();
    this.search();
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
</style>
